package com.jinchengll.xigua.repository;

import com.jinchengll.xigua.entity.BaseResponse;
import com.jinchengll.xigua.entity.Page;
import com.jinchengll.xigua.entity.Video;
import com.jinchengll.xigua.network.INetworkClient;
import com.jinchengll.xigua.network.RetrofitClient;
import com.jinchengll.xigua.network.base.BaseObserver;
import com.jinchengll.xigua.network.service.HomeService;
import com.jinchengll.xigua.network.service.VideoService;

import java.util.List;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * 中间层-数据仓库-实现类
 *
 * @author jinchengll
 * @since 2021/10/3
 */
public class Repository implements IRepository {

    // 单例模式，饿汉模式直接加载，后续有性能问题再改为懒加载
    public static Repository instance = new Repository();

    private final INetworkClient networkClient;
    private final VideoService videoService;
    private final HomeService homeService;

//    // 持久层
//    private final IDao dao;

    private Repository() {
        networkClient = RetrofitClient.getInstance();
        videoService = networkClient.getService(VideoService.class);
        homeService = networkClient.getService(HomeService.class);
//        dao = new SPDao();
    }

    @Override
    public void getVideoPage(int pageNo, int PageSize, BaseObserver<Page<Video>> observer) {
        Observable<BaseResponse<Page<Video>>> observable = videoService.page(pageNo, PageSize);
        observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(observer);
    }

    // 应该带有缓存功能，一次应用启动周期内只访问一次网络请求该数据
    @Override
    public void getHomeItems(BaseObserver<List<String>> observer) {
//        String key = "home_items";
//        Observable<BaseResponse<List<String>>> observable;
        // 判断是否存在，相对来说速度较快，后面有性能瓶颈可加入异步
//        if (dao.isSaved(key)) {
//            observable = Observable.create(e -> {
//                List<String> value = dao.getValue(key, ArrayList.class);
//                // 封装返回对象
//                BaseResponse<List<String>> response = new BaseResponse<>();
//                response.setCode(200);
//                response.setData(value);
//                e.onNext(response);
//            });
//        } else {
//            observable = homeService.getItems();
//        }
        Observable<BaseResponse<List<String>>> observable = homeService.getItems();
        observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(observer);
    }

}
